package com.exam.service.privilege.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.exam.bean.privilege.Employee;
import com.exam.service.base.DaoSupport;
import com.exam.service.privilege.EmployeeService;

@Service
@Transactional
public class EmployeeServiceBean extends DaoSupport implements EmployeeService {

	@Transactional(readOnly=true, propagation=Propagation.NOT_SUPPORTED)
	public boolean exist(String entityid) {
		
		Long count = (Long)em.createQuery("select count(o) from Employee o where o.username=?1").setParameter(1, entityid).getSingleResult();
		return count>0;
	}
	
	@Transactional(readOnly=true, propagation=Propagation.NOT_SUPPORTED)
	public boolean existCardno(String cardno) {
		
		Long count = (Long)em.createQuery("select count(o) from IDCard o where o.cardno=?1").setParameter(1, cardno).getSingleResult();
		return count>0;
	}
	
	public boolean updatePassword(String username, String oldpass, String newpass) {
		// TODO Auto-generated method stub
		Query query=em.createQuery("update Employee o set o.password=?1 where o.username=?2 and o.password=?3");
		query.setParameter(1, newpass);
		query.setParameter(2, username);
		query.setParameter(3, oldpass);
		return query.executeUpdate()>0;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Employee userLogin(String username,String password){
		
		Query query=em.createQuery("select o from Employee o where o.username=?1 and password=?2");
		query.setParameter(1, username);
		query.setParameter(2, password);
		List<Employee> users=query.getResultList();
		return (users==null || users.size()==0)?null:(Employee)users.get(0);
	}
	
	public void setVisible(String[] entityids,Boolean status){
		
		if(entityids!=null&&entityids.length>0){
			StringBuffer jpql=new StringBuffer("");
			int i=0;
			for(;i<entityids.length-1;i++){
				jpql.append("?").append(i+2).append(",");
			}
			jpql.append("?").append(i+2);
			Query query=em.createQuery("update Employee o set o.visible=?1 where o.username in("+jpql.toString()+")")
			.setParameter(1, status);
			for(i=0;i<entityids.length;i++){
				query.setParameter(i+2, entityids[i]);
			}
			query.executeUpdate();
		}
	}
}
